package myservice.android.activities;

import java.util.ArrayList;

import myservice.android.Global;
import myservice.android.R;
import myservice.android.database.Database;
import myservice.android.utilities.PopupMenu;
import myservice.android.utilities.Record;
import myservice.android.utilities.RecordAdapter;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

public class TerritoryListActivity extends BaseActivity {
	
	private Button addTerritoryButton;
	private ArrayList<Record> territoryData;
	private ListView territoryList;
	private TextView noTerritoriesDefinedText;
	private RecordAdapter territoryAdapter;

	private int mode; // 0 = modify; 1 = pick from list
	
	@Override
	protected void initializeLayoutIdAndTitle() {

		layoutId = R.layout.territory_list;		
		
	}

	@Override
	protected void retrieveViews() {

        addTerritoryButton = (Button) findViewById(R.id.addTerritoryButton);
        territoryList = (ListView) findViewById(R.id.territoriesList);
        noTerritoriesDefinedText = (TextView) findViewById(R.id.noTerritoriesMessage);
		
	}

	@Override
	protected void loadActivityParameters() {

		mode = activityParameters.getInt("mode");
		
	}

	@Override
	protected void assignListeners() {

        addTerritoryButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				final Dialog dialog = new Dialog(TerritoryListActivity.this);
				dialog.setContentView(R.layout.add_territory_dialog);
				dialog.setTitle(Global.res.getString(R.string.title_add_new_territory));
				
				Button saveButton = (Button) dialog.findViewById(R.id.saveButton);				
				Button cancelButton = (Button) dialog.findViewById(R.id.cancelButton);
				final EditText nameField = (EditText) dialog.findViewById(R.id.nameField);
				
				saveButton.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View arg0) {					
						Database.execSQL("INSERT INTO territories (territoryid,type,parent,name,comments,completed,timestamp) VALUES ("+Database.getUniqueRowId("territories")+
								         ",0,0,'"+Global.fixText(nameField.getText())+"','',0,"+Global.getTimeStamp()+")");	
						dialog.dismiss();
						updateList();
					}			
				});
				
				cancelButton.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View arg0) {
						dialog.dismiss();				
					}			
				});		
				
				dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);								
				dialog.show();																		
			}
        }); 
		
	}		       
    
	private void updateList() {
		
		PopupMenu.createPopupMenu(this);	
		PopupMenu.menuSection4.setVisibility(View.GONE);
		
		territoryData = new ArrayList<Record>();
		
    	Cursor cursor = Database.select("SELECT * FROM territories WHERE type=0 AND timestamp<>"+Global.TIMESTAMP_DELETED+" ORDER BY completed,name");
    	
    	boolean noTerritoriesDefined = true;

    	while (cursor.moveToNext()) {
    		noTerritoriesDefined=false;
    		Record territory = new Record();
    		territory.id=cursor.getInt(cursor.getColumnIndex("territoryid"));
    		territory.firstLine=cursor.getString(cursor.getColumnIndex("name"));
    		territory.secondLine=cursor.getString(cursor.getColumnIndex("comments"));
    		territory.completed=cursor.getInt(cursor.getColumnIndex("completed")); 		
    		territoryData.add(territory);
    	}	
    	cursor.close();    	 
    	
    	if (noTerritoriesDefined==true)
    		noTerritoriesDefinedText.setVisibility(View.VISIBLE);
    	else
    		noTerritoriesDefinedText.setVisibility(View.GONE);
    	
        territoryAdapter = new RecordAdapter(this, R.layout.list_row, territoryData, 3);
        territoryList.setAdapter(territoryAdapter);
        
        territoryList.setOnItemLongClickListener(new OnItemLongClickListener () {

			@Override
			public boolean onItemLongClick(AdapterView<?> parent, View view,
					int position, long id) {
				
				final long tid = territoryData.get(position).id;
				final int completed = territoryData.get(position).completed;
				
				PopupMenu.menuHeading.setText(territoryData.get(position).firstLine);
				
				PopupMenu.menuOption1.setText(Global.res.getString(R.string.menuitem_modify_territory));				
				if (completed==0)
					PopupMenu.menuOption2.setText(Global.res.getString(R.string.menuitem_territory_mark_completed));
				else
					PopupMenu.menuOption2.setText(Global.res.getString(R.string.menuitem_territory_mark_not_completed));				
				PopupMenu.menuOption3.setText(Global.res.getString(R.string.menuitem_delete_territory));				
				
				PopupMenu.menuOption1.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View arg0) {
						PopupMenu.closeMenu();
						clickTerritory(tid);				
					}					
				});		
				
				PopupMenu.menuOption2.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View arg0) {
						PopupMenu.closeMenu();						
						int c = (completed + 1) % 2;													
						Database.execSQL("UPDATE territories SET completed="+c+", timestamp="+Global.getTimeStamp()+" WHERE territoryid="+tid);						
						updateList();
					}					
				});				
				
				PopupMenu.menuOption3.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View arg0) {
						PopupMenu.closeMenu();
						AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(TerritoryListActivity.this);
						alertDialogBuilder.setTitle(Global.res.getText(R.string.title_warning));				
						alertDialogBuilder
							.setMessage(Global.res.getText(R.string.message_delete_territory_confirmation))
							.setPositiveButton(Global.res.getText(R.string.button_yes),new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,int id) {
									Database.deleteTerritoryElement(tid);							    	
									updateList();
								}
							  })
							.setNegativeButton(Global.res.getText(R.string.button_no),new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog, int id) {
									dialog.cancel();
								}
							});
				 
						AlertDialog alertDialog = alertDialogBuilder.create();
						alertDialog.show();		
					}					
				});					
				
				PopupMenu.showMenu(view);				
				
				return true;
			}
        	
        });
        
        territoryList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position,
					long id) {				
					clickTerritory(territoryData.get(position).id);
			}
        	
        });
    	
	}	
	
	private void clickTerritory(long tid) {
		Intent i = new Intent(getApplicationContext(),TerritoryElementActivity.class);
		i.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
		i.putExtra("territory_id",tid);
		i.putExtra("mode", mode);
		startActivity(i);	
	}

	@Override
	protected void updateUi() {
		
    	if (Global.selectedId!=0) // A house/apartment was picked from the list
    		finish();

        if (mode==0)
        	activityTitleView.setText(Global.res.getString(R.string.title_territories));
        else
        	activityTitleView.setText(Global.res.getString(R.string.title_select_territory));  
        
        updateList();
		
	}
    
    
}